<template>
  <div class="dish-detail-container" v-loading="loading">
    <!-- 返回按钮 -->
    <div class="back-button-container">
      <el-button 
        type="primary" 
        :icon="ArrowLeft" 
        @click="goBack"
        class="back-button"
      >
        返回
      </el-button>
    </div>
    
    <el-card v-if="dish">
      <el-row :gutter="30">
        <el-col :span="10">
          <div class="image-container">
            <img
              :src="getImageUrl(dish.dishImage || '')"
              class="detail-image"
              @error="handleImageError"
            />
          </div>
        </el-col>
        <el-col :span="14">
          <div class="detail-info">
            <div class="detail-header">
              <h1 class="dish-title">{{ dish.dishName }}</h1>
              <el-button
                :type="isFavorite ? 'danger' : 'default'"
                :icon="isFavorite ? StarFilled : Star"
                @click="toggleFavorite"
                circle
              />
            </div>
            
            <div class="meta-info">
              <el-tag size="large" type="success">{{ dish.dishType }}</el-tag>
              <el-tag size="large" v-if="dish.dishStatus === '1'" type="danger">停售</el-tag>
              <span class="sales-info">已售 {{ dish.salesCount || 0 }} 份</span>
            </div>

            <div class="price-section">
              <span class="current-price">¥{{ dish.dishPrice }}</span>
            </div>

            <el-divider />

            <div class="info-section">
              <h3>菜品描述</h3>
              <p>{{ dish.dishDescription || '暂无描述' }}</p>
            </div>

            <div class="info-section" v-if="dish.dishSpecification">
              <h3>规格</h3>
              <p>{{ dish.dishSpecification }}</p>
            </div>

            <div class="info-section" v-if="dish.dishMaterials">
              <h3>食材</h3>
              <p>{{ dish.dishMaterials }}</p>
            </div>

            <el-divider />

            <div class="action-section">
              <el-input-number
                v-model="quantity"
                :min="1"
                :max="99"
                :disabled="dish.dishStatus === '1'"
              />
              <el-button
                type="primary"
                size="large"
                :icon="ShoppingCart"
                :disabled="dish.dishStatus === '1'"
                @click="addToCart"
                class="add-cart-btn"
              >
                加入购物车
              </el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>

    <!-- 评论区 -->
    <el-card class="comments-section" v-if="dish">
      <div class="comments-header">
        <h2>用户评价 ({{ comments.length }})</h2>
        <el-button 
          type="primary" 
          :icon="Edit" 
          @click="showCommentDialog"
          class="add-comment-btn"
        >
          发表评论
        </el-button>
      </div>

      <el-empty v-if="comments.length === 0" description="暂无评价" />

      <div class="comments-list">
        <transition-group name="comment-fade">
          <div class="comment-item" v-for="comment in comments" :key="comment.commentId">
            <div class="comment-header">
              <div class="user-info">
                <el-avatar :size="40">{{ comment.user?.nickname?.charAt(0) || 'U' }}</el-avatar>
                <div class="user-details">
                  <span class="username">{{ comment.user?.nickname || '匿名用户' }}</span>
                  <el-rate v-model="comment.rating" disabled size="small" />
                </div>
              </div>
              <div class="comment-actions">
                <span class="comment-time">{{ formatTime(comment.createTime) }}</span>
                <el-button
                  v-if="userStore.userId && comment.userId === userStore.userId"
                  type="danger"
                  size="small"
                  @click="handleDeleteComment(comment.commentId!)"
                  class="delete-comment-btn"
                >
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </div>
            </div>
            <div class="comment-content">
              {{ comment.commentContent }}
            </div>
            <div class="comment-images" v-if="comment.commentImages && comment.commentImages.trim()">
              <div class="comment-image-gallery">
                <img
                  v-for="(imageUrl, index) in getCommentImages(comment.commentImages)"
                  :key="index"
                  :src="getImageUrl(imageUrl)"
                  class="comment-image"
                  @click="previewCommentImage(imageUrl)"
                  @error="handleCommentImageError"
                  alt="评论图片"
                />
              </div>
            </div>
          </div>
        </transition-group>
      </div>
    </el-card>

    <!-- 发表评论对话框 -->
    <el-dialog
      v-model="showCommentForm"
      title="发表评论"
      width="500px"
      @close="resetCommentForm"
    >
      <el-form :model="commentForm" :rules="commentRules" ref="commentFormRef" label-width="80px">
        <el-form-item label="评分" prop="rating">
          <el-rate v-model="commentForm.rating" :max="5" show-text />
        </el-form-item>
        <el-form-item label="评论图片">
          <div class="comment-image-upload-container">
            <el-upload
              class="comment-image-uploader"
              :show-file-list="false"
              :before-upload="beforeCommentImageUpload"
              :http-request="handleCommentImageUpload"
              accept="image/*"
            >
              <el-image
                v-if="commentForm.commentImages && commentForm.commentImages.trim()"
                :src="getImageUrl(commentForm.commentImages)"
                class="uploaded-comment-image"
                fit="cover"
                @error="handleCommentImageError"
              />
              <el-icon v-else class="comment-image-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="comment-image-actions" v-if="commentForm.commentImages">
              <el-button size="small" @click="commentForm.commentImages = ''">删除图片</el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="评论内容" prop="commentContent">
          <el-input
            v-model="commentForm.commentContent"
            type="textarea"
            :rows="4"
            placeholder="请输入您的评价..."
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCommentForm = false">取消</el-button>
        <el-button type="primary" @click="submitComment" :loading="submitting">
          发表评论
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, reactive } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Star, StarFilled, ShoppingCart, ArrowLeft, Edit, Plus, Delete } from '@element-plus/icons-vue';
import { getDishById } from '@/api/dish';
import { getCommentsByDishId, createDishComment, deleteComment } from '@/api/comment';
import { getUserFavorites, addFavorite, deleteFavoriteByUserAndDish } from '@/api/favorite';
import { getUserById } from '@/api/user';
import { uploadFile } from '@/api/file';
import { useCartStore } from '@/stores/cart';
import { useUserStore } from '@/stores/user';
import type { Dish, Comment, Favorite, CreateCommentRequest } from '@/types';
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';

const route = useRoute();
const router = useRouter();
const cartStore = useCartStore();
const userStore = useUserStore();

const dish = ref<Dish | null>(null);
const comments = ref<Comment[]>([]);
const quantity = ref(1);
const loading = ref(false);
const favorites = ref<Favorite[]>([]);
const showCommentForm = ref(false);
const submitting = ref(false);
const commentFormRef = ref<FormInstance>();

const commentForm = reactive({
  rating: 5,
  commentContent: '',
  commentImages: ''
});

const commentRules: FormRules = {
  rating: [{ required: true, message: '请选择评分', trigger: 'change' }],
  commentContent: [
    { required: true, message: '请输入评论内容', trigger: 'blur' },
    { min: 5, message: '评论内容至少5个字符', trigger: 'blur' }
  ]
};

const dishId = computed(() => Number(route.params.id));

const isFavorite = computed(() => {
  if (!userStore.userId || !dish.value) return false;
  return favorites.value.some(f => f.dishId === dish.value!.dishId);
});

// 加载菜品详情
const loadDishDetail = async () => {
  loading.value = true;
  try {
    const response = await getDishById(dishId.value);
    if (response.operateResult === 'SUCC' && response.data) {
      dish.value = response.data;
    } else {
      ElMessage.error('加载菜品详情失败');
    }
  } catch (error) {
    ElMessage.error('加载菜品详情失败');
  } finally {
    loading.value = false;
  }
};

// 加载评论
const loadComments = async () => {
  try {
    const response = await getCommentsByDishId(dishId.value);
    if (response.operateResult === 'SUCC' && response.data) {
      // 加载每个评论的用户信息
      const commentsWithUsers = await Promise.all(
        response.data.map(async (comment) => {
          try {
            const userRes = await getUserById(comment.userId);
            if (userRes.operateResult === 'SUCC' && userRes.data) {
              return { ...comment, user: userRes.data };
            }
            return comment;
          } catch (error) {
            return comment;
          }
        })
      );
      comments.value = commentsWithUsers;
    } else {
      comments.value = [];
    }
  } catch (error) {
    console.error('加载评论失败:', error);
    comments.value = [];
  }
};

// 加载收藏状态
const loadFavoriteStatus = async () => {
  if (!userStore.userId) return;
  try {
    const response = await getUserFavorites(userStore.userId);
    if (response.operateResult === 'SUCC' && response.data) {
      favorites.value = response.data;
    }
  } catch (error) {
  }
};

// 切换收藏状态
const toggleFavorite = async () => {
  if (!userStore.userId) {
    ElMessage.warning('请先登录');
    return;
  }

  if (!dish.value) return;

  try {
    if (isFavorite.value) {
      // 取消收藏
      await deleteFavoriteByUserAndDish(userStore.userId, dish.value.dishId!);
      ElMessage.success('已取消收藏');
    } else {
      // 添加收藏
      await addFavorite({
        userId: userStore.userId,
        dishId: dish.value.dishId!
      });
      ElMessage.success('收藏成功');
    }
    await loadFavoriteStatus();
  } catch (error) {
    ElMessage.error('操作失败');
  }
};

// 加入购物车
const addToCart = async () => {
  if (!userStore.userId) {
    ElMessage.warning('请先登录');
    return;
  }

  if (!dish.value) return;

  if (dish.value.dishStatus === '1') {
    ElMessage.warning('该菜品已停售');
    return;
  }

  await cartStore.addItem(userStore.userId, dish.value.dishId!, quantity.value);
  quantity.value = 1;
};

// 格式化时间 - 显示完整日期时间
const formatTime = (time?: string) => {
  if (!time) return '';
  const date = new Date(time);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  });
};

// 获取评论图片数组
const getCommentImages = (commentImages: string) => {
  if (!commentImages || !commentImages.trim()) {
    return [];
  }
  return commentImages.split(',').map(url => url.trim()).filter(url => url);
};

// 获取图片URL
const getImageUrl = (imagePath: string) => {
  if (!imagePath || !imagePath.trim()) {
    return 'https://via.placeholder.com/500x400?text=No+Image';
  }
  if (imagePath.startsWith('http')) {
    return imagePath;
  }
  return `http://localhost:8060${imagePath}`;
};

// 预览评论图片
const previewCommentImage = (imagePath: string) => {
  if (!imagePath || !imagePath.trim()) {
    ElMessage.warning('图片路径无效');
    return;
  }
  
  try {
    const imageUrl = getImageUrl(imagePath);
    
    // 创建图片预览窗口
    const previewWindow = window.open('', '_blank', 'width=800,height=600,scrollbars=yes,resizable=yes');
    if (previewWindow) {
      previewWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
          <title>图片预览</title>
          <style>
            body {
              margin: 0;
              padding: 20px;
              background: #000;
              display: flex;
              justify-content: center;
              align-items: center;
              min-height: 100vh;
            }
            img {
              max-width: 100%;
              max-height: 100%;
              object-fit: contain;
              border-radius: 8px;
              box-shadow: 0 4px 20px rgba(255, 255, 255, 0.1);
            }
            .close-btn {
              position: fixed;
              top: 20px;
              right: 20px;
              background: rgba(255, 255, 255, 0.2);
              color: white;
              border: none;
              padding: 10px 20px;
              border-radius: 5px;
              cursor: pointer;
              font-size: 16px;
            }
            .close-btn:hover {
              background: rgba(255, 255, 255, 0.3);
            }
          </style>
        </head>
        <body>
          <button class="close-btn" onclick="window.close()">关闭</button>
          <img src="${imageUrl}" alt="评论图片" onerror="this.src='https://via.placeholder.com/500x400?text=图片加载失败'">
        </body>
        </html>
      `);
      previewWindow.document.close();
    } else {
      ElMessage.error('无法打开图片预览窗口，请检查浏览器设置');
    }
  } catch (error) {
    console.error('预览图片失败:', error);
    ElMessage.error('预览图片失败');
  }
};

// 图片加载错误处理
const handleImageError = (e: Event) => {
  const target = e.target as HTMLImageElement;
  target.src = 'https://via.placeholder.com/500x400?text=No+Image';
};

// 返回上一页
const goBack = () => {
  router.back();
};

// 显示评论对话框
const showCommentDialog = () => {
  if (!userStore.userId) {
    ElMessage.warning('请先登录');
    return;
  }
  showCommentForm.value = true;
};

// 提交评论
const submitComment = async () => {
  if (!commentFormRef.value) return;
  
  await commentFormRef.value.validate(async (valid) => {
    if (!valid) return;
    
    if (!userStore.userId || !dish.value) {
      ElMessage.error('用户信息或菜品信息不完整');
      return;
    }
    
    submitting.value = true;
    try {
      // 直接对菜品评论，不需要订单ID
      const commentData: CreateCommentRequest = {
        userId: userStore.userId,
        dishId: dish.value.dishId!,
        rating: commentForm.rating,
        commentContent: commentForm.commentContent,
        commentImages: commentForm.commentImages || '',
        commentStatus: '0'
      };
      
      const response = await createDishComment(commentData);
      if (response.operateResult === 'SUCC') {
        ElMessage.success('评论发表成功');
        showCommentForm.value = false;
        await loadComments();
      } else {
        ElMessage.error(response.errorMsg || '评论发表失败');
      }
    } catch (error: any) {
      ElMessage.error(error.message || '评论发表失败');
    } finally {
      submitting.value = false;
    }
  });
};

// 重置评论表单
const resetCommentForm = () => {
  commentFormRef.value?.resetFields();
  commentForm.rating = 5;
  commentForm.commentContent = '';
  commentForm.commentImages = '';
};

// 评论图片上传前验证
const beforeCommentImageUpload = (file: File) => {
  const isImage = file.type.startsWith('image/');
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!');
    return false;
  }
  return true;
};

// 处理评论图片上传
const handleCommentImageUpload = async (options: any) => {
  const { file } = options;
  try {
    const response = await uploadFile(file);
    if (response.operateResult === 'SUCC' && response.data) {
      commentForm.commentImages = response.data;
      ElMessage.success('图片上传成功');
    } else {
      ElMessage.error(response.errorMsg || '图片上传失败');
    }
  } catch (error: any) {
    ElMessage.error(error.message || '图片上传失败');
  }
};

// 处理评论图片加载错误
const handleCommentImageError = (error: any) => {
  ElMessage.error('图片加载失败，请重新上传');
};

// 删除评论
const handleDeleteComment = (commentId: number) => {
  ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await deleteComment(commentId);
      if (response.operateResult === 'SUCC') {
        ElMessage.success('评论删除成功');
        await loadComments();
      } else {
        ElMessage.error(response.errorMsg || '删除失败');
      }
    } catch (error: any) {
      ElMessage.error(error.message || '删除失败');
    }
  }).catch(() => {});
};

onMounted(() => {
  loadDishDetail();
  loadComments();
  loadFavoriteStatus();
});
</script>

<style scoped>
.dish-detail-container {
  animation: fadeIn 0.5s ease-out;
  position: relative;
}

.back-button-container {
  margin-bottom: 20px;
}

.back-button {
  border-radius: 12px;
  font-weight: 600;
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}

.back-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(64, 158, 255, 0.4);
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.image-container {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.detail-image {
  width: 100%;
  height: 400px;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.detail-image:hover {
  transform: scale(1.05);
}

.detail-info {
  padding: 10px 0;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.dish-title {
  margin: 0;
  font-size: 28px;
  font-weight: bold;
  color: #303133;
}

.meta-info {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 20px;
}

.sales-info {
  color: #909399;
  font-size: 14px;
}

.price-section {
  margin: 20px 0;
}

.current-price {
  font-size: 36px;
  font-weight: bold;
  color: #f56c6c;
}

.info-section {
  margin: 20px 0;
}

.info-section h3 {
  font-size: 16px;
  color: #606266;
  margin-bottom: 10px;
}

.info-section p {
  color: #909399;
  line-height: 1.6;
}

.action-section {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-top: 30px;
}

.add-cart-btn {
  flex: 1;
  height: 50px;
  font-size: 16px;
}

.comments-section {
  margin-top: 20px;
  animation: slideUp 0.5s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.comments-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.comments-header h2 {
  font-size: 22px;
  color: #303133;
  margin: 0;
}

.add-comment-btn {
  border-radius: 12px;
  font-weight: 600;
  box-shadow: 0 4px 16px rgba(64, 158, 255, 0.3);
  transition: all 0.3s ease;
}

.add-comment-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(64, 158, 255, 0.4);
}

.comments-list {
  margin-top: 20px;
}

.comment-item {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  transition: background-color 0.3s ease;
}

.comment-item:hover {
  background-color: #f5f7fa;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.username {
  font-weight: bold;
  color: #303133;
}

.comment-time {
  color: #909399;
  font-size: 12px;
}

.comment-content {
  color: #606266;
  line-height: 1.6;
  padding-left: 52px;
}

.comment-fade-enter-active,
.comment-fade-leave-active {
  transition: all 0.3s ease;
}

.comment-fade-enter-from {
  opacity: 0;
  transform: translateX(-20px);
}

.comment-fade-leave-to {
  opacity: 0;
  transform: translateX(20px);
}

/* 评论图片上传样式 */
.comment-image-upload-container {
  border-radius: 12px;
  overflow: hidden;
}

.comment-image-uploader {
  border: 2px dashed #cbd5e0;
  border-radius: 12px;
  width: 200px;
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
  transition: all 0.3s ease;
  cursor: pointer;
}

.comment-image-uploader:hover {
  border-color: #667eea;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.05) 0%, rgba(118, 75, 162, 0.05) 100%);
  transform: translateY(-2px);
  box-shadow: 0 8px 24px rgba(102, 126, 234, 0.15);
}

.uploaded-comment-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 12px;
}

.comment-image-uploader-icon {
  font-size: 32px;
  color: #a0aec0;
  transition: all 0.3s ease;
}

.comment-image-uploader:hover .comment-image-uploader-icon {
  color: #667eea;
  transform: scale(1.1);
}

.comment-image-actions {
  margin-top: 12px;
  text-align: center;
}

/* 评论图片显示样式 */
.comment-images {
  margin-top: 12px;
  padding-left: 52px;
}

.comment-image-gallery {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.comment-image {
  width: 120px;
  height: 90px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  object-fit: cover;
  display: block;
}

.comment-image:hover {
  opacity: 0.8;
  transform: scale(1.02);
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
}

/* 评论操作区域样式 */
.comment-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.delete-comment-btn {
  border-radius: 8px;
  font-weight: 600;
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(245, 101, 101, 0.2);
}

.delete-comment-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(245, 101, 101, 0.3);
}
</style>

